<script setup>

import { ref, reactive, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { CaretDownOutlined, CaretUpOutlined, RedoOutlined } from '@ant-design/icons-vue'
import utils from "@/common/utils/utils.js";
import { useStore } from "vuex";
import request from "@/common/utils/request";
import {
    risk_types_baseData
} from '@/views/shotstack/MuseMixedCut/utools/index.js'
// id生成
import { nanoid } from "nanoid";
import { message } from 'ant-design-vue';


const emit = defineEmits(['testStart:data', 'testOver:data'])

const store = useStore();

const props = defineProps({
    // tts_id: {
    //     type: String,
    //     default: ''
    // },
    disableSubmit: {
        type: Boolean,
        default: false
    },
    type: {
        type: String,
        default: 'tts_config'
    },
    text_arr: {
        type: Array,
        default: () => {
            return []
        }
    },
    risk_data: {
        type: Object || null,
        default: () => {
            return null
        }
    }
})

onMounted(() => {
    console.log(props, 'props传参');
    if (props.risk_data) {
        risk_types.value = JSON.parse(JSON.stringify(props.risk_data))
    }
    // debugger
})

// 抽屉中的使用缓存数据
const subTitle = computed(() => {
    return store.state.videoMixCut.Subtitles;
});

// 当前预览的视频组下标
const currentDrawerIndex = computed(() => {
    return store.state.videoMixCut.currentIndex;
});

// 风险词手风琴是否展开
const riskword = ref('')
// 风险词检测按钮文本
const textFrobiddenText = ref('开始检测')

const riskwordLoding = ref(false)

// 风险词暂存字段
const riskObj = ref({
    "filtered_data": [],
    "total_word_counts": {
        "low_risk": {},
        "high_risk": {},
        "medium_risk": {}
    }
})

// 风险类型
const risk_types = ref(
    [
        {
            name: '高风险',
            id: 'high_risk',
            bgcolor: '#ffb6b6',
            textcolor: '#FF4D4F',
            // text- 风险文案
            // tags- 触发的风险词
            risk_text: [], // 风险文案数组
        },
        {
            name: '中风险',
            id: 'medium_risk',
            textcolor: '#FAAD14',
            bgcolor: '#ffe8b7',
            risk_text: [], // 风险文案数组
        },
        {
            name: '低风险',
            id: 'low_risk',
            bgcolor: '#cdfeb6',
            textcolor: '#55C51F',
            risk_text: [], // 风险文案数组
        },
        {
            name: '自定义风险词',
            id: 'custom_risk',
            bgcolor: '#bcb8fe',
            textcolor: '#5C53FF',
            risk_text: [], // 风险文案数组
        },
    ])

// 赋值risk_types
const setRisk_types = (data) => {
    !!data ? (risk_types.value = data) : (risk_types.value = risk_types_baseData)

}


// 过滤没有的关键词
const filterRisk_types = computed(() => {
    const arr = risk_types.value.filter(e => e.risk_text.length) || []
    console.log(arr, '过滤的arr');
    return arr
})

// 风险词检测
const textFrobidden = async () => {
    emit('testStart')

    if (!props.text_arr.length) return
    riskwordLoding.value = true
    try {
        const res = await request.post("/work_ai", "/user/shotstack/banned/check", {
            text: props.text_arr,
            customRiskStr: ''
        })
        console.log(res, '风险词检测结果');
        // console.log(JSON.parse(res.output), '风险词检测结果');
        const resData = res.result
        riskObj.value = resData
        debugger
        if (resData.filtered_data.length) {
            // 置空当前的风险词列表
            risk_types.value.forEach(ele => ele.risk_text = [])
            // 重置操作按钮的文本
            textFrobiddenText.value = '开始检测'
            resData.filtered_data.forEach(ele => {
                const keys = Object.keys(ele.hit_risk_words)

                keys.forEach((key, index) => {
                    const find = risk_types.value.find(i => i.id == key)
                    if (find) {
                        // debugger
                        const riskTag = Object.keys(ele.hit_risk_words[key])

                        find.risk_text.push({
                            text: ele.text,
                            tags: riskTag,
                            id: nanoid()
                        })
                    }
                })

            })
            console.log(risk_types.value, 'risk_types.value');
        } else {
            message.warning('暂未发现风险词!')
            textFrobiddenText.value = '重新检测'
        }
        emit('testOver', JSON.parse(JSON.stringify(risk_types.value)))
    } catch (error) {
        console.log(error)
        emit('testOver', null)
    } finally {
        riskwordLoding.value = false
    }
}

// 防抖函数
const debounceTextFrobidden = utils.debounce(500, textFrobidden)

// 展开或者折起手风琴
const foldOrOpen = (type = undefined) => {
    if (type != undefined) {
        riskword.value = type
    } else {
        riskword.value = riskword.value == '1' ? '' : '1'

    }
}

defineExpose({
    debounceTextFrobidden,
    foldOrOpen,
    setRisk_types
})
</script>

<template>
    <div class="risk_word_box">
        <a-collapse v-model:activeKey="riskword" :expandIcon="() => { }" @change="(e) => riskword = e.length ? '1' : ''"
            ghost>
            <a-collapse-panel key="1">
                <template #header>
                    <div style="display: flex; align-items: center; gap: 5px;">
                        <span>风险词检测</span>
                        <CaretDownOutlined v-show="riskword != 1" class="downOutlined"></CaretDownOutlined>
                        <CaretUpOutlined class="downOutlined" v-show="riskword == 1"></CaretUpOutlined>
                    </div>
                </template>
                <div class="risk_word_content">

                    <div class="aging_btn">
                        <a-button v-show="filterRisk_types.length" :loading="riskwordLoding"
                            :disabled="props.disableSubmit" type="link" @click="debounceTextFrobidden"><redo-outlined
                                style="margin-right: 3px;" />重新检测</a-button>
                    </div>

                    <template v-if="filterRisk_types.length">
                        <div class="risk_show_box">
                            <div class="risk_word_item" v-for="i in filterRisk_types" :key="i.id">
                                <div class="risk_title_box" :style="{
                                    color: i.textcolor,
                                    background: `linear-gradient(to right, ${i.bgcolor}, rgba(255, 87, 51, 0))`
                                }">
                                    <span class="risk_title">* {{ i.name }}</span>
                                </div>
                                <div class="risk_word_list">
                                    <div class="risk_list_item" v-for="(ele, index) in i.risk_text" :key="ele.id">
                                        <span :style="{
                                            color: i.textcolor,
                                        }" class="risk_title">{{ ele.tags.map(ele => ele).join('、') }}</span>
                                        <span class="risk_text">{{ ++index + '、' }} {{ ele.text }}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </template>

                    <template v-else>
                        <a-button type="primary" class="btn" @click="debounceTextFrobidden" :loading="riskwordLoding"
                            :disabled="props.disableSubmit">
                            {{ textFrobiddenText }}
                        </a-button>
                    </template>
                </div>
            </a-collapse-panel>
        </a-collapse>
    </div>
</template>

<style lang="less" scoped>
// 风险词匹配展示
.risk_word_box {

    :deep(.ss-collapse-item) {
        .ss-collapse-header {
            padding: 0;
            margin-top: 16px;

            &:hover {
                color: var(--ss-primary-6);
            }
        }

        .ss-collapse-content-box {
            padding: 0 !important
        }
    }

    .risk_word_content {
        background: #fff;
        min-height: 200px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;


        .btn {
            width: 50%;
            border-radius: 5px;
        }

        .aging_btn {
            width: 100%;
            display: flex;
            justify-content: end;

            :deep(.ss-btn) {
                span {
                    margin: 0;
                }
            }

        }

        .risk_show_box {
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: space-between;
            padding: 8px;
            gap: 5px;

            // 风险词每一项
            .risk_word_item {
                flex: 1;
                border: 1px solid #dde2e9;
                border-radius: 10px;

                // 每一个风险词卡片的标题
                .risk_title_box {
                    line-height: 30px;
                    font-weight: 900;
                    padding-left: 10px;
                    border-radius: 10px 10px 0 0;
                }

                // 触发的风险词列表
                .risk_word_list {
                    display: flex;
                    flex-direction: column;
                    padding: 8px;
                    gap: 14px;

                    .risk_list_item {
                        display: flex;
                        flex-direction: column;
                        border-bottom: 1px solid #dde2e9;
                        gap: 10px;
                        padding-bottom: 7px;

                        &:last-child {
                            border-bottom: none;
                        }

                        .risk_title {
                            font-size: 16px;
                            // font-weight: 900;
                        }

                        .risk_text {
                            font-size: 13px;
                            color: #737a87;
                        }
                    }
                }
            }
        }
    }
}
</style>